<template>
  <el-card class="box-card" tabindex="-1">
    <!-- 用户密码修改表单 -->
    <el-form
      ref="form"
      :rules="rules"
      :model="passwordForm"
      label-width="120px"
      class="password-form"
    >
      <el-form-item label="当前密码" prop="currentPassword">
        <el-input
          type="password"
          v-model="passwordForm.currentPassword"
        ></el-input>
      </el-form-item>
      <el-form-item label="新密码" prop="newPassword">
        <el-input type="password" v-model="passwordForm.newPassword"></el-input>
      </el-form-item>
      <el-form-item label="确认密码" prop="confirmPassword">
        <el-input
          type="password"
          v-model="passwordForm.confirmPassword"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="changePassword">修改密码</el-button>
      </el-form-item>
    </el-form>

    <!-- 文件上传 -->
    <!-- <el-upload class="avatar-uploader" action="/upload" :show-file-list="false" :on-success="handleAvatarSuccess"
      :before-upload="beforeAvatarUpload">
    </el-upload> -->
  </el-card>
</template>
<style scoped>
.box-card {
  margin-top: 25px;
}

.password-form {
  margin-bottom: 20px;
}
</style>
<script setup>
import { reactive, ref } from 'vue'

const passwordForm = reactive({
  currentPassword: '',
  newPassword: '',
  confirmPassword: ''
})
const form = ref()

const rules = {
  currentPassword: [
    { required: true, message: '请输入之前的密码', trigger: 'blur' },
    { min: 2, max: 10, message: '用户名必须是 2-10位 的字符', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入需要修改的密码', trigger: 'blur' },
    {
      pattern: /^\S{6,15}$/,
      message: '密码必须是 6-15位 的非空字符',
      trigger: 'blur'
    }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    {
      pattern: /^\S{6,15}$/,
      message: '密码必须是 6-15位 的非空字符',
      trigger: 'blur'
    },
    {
      validator: (rule, value, callback) => {
        // 判断 value 和 当前 form 中收集的 password 是否一致
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入密码不一致'))
        } else {
          console.log('校验成功')
          callback() // 就算校验成功，也需要callback
        }
      },
      trigger: 'blur'
    }
  ]
}

const changePassword = async () => {
  // 在这里处理密码修改逻辑
  console.log('修改密码', passwordForm)
  await form.value.validate((valid) => {
    if (valid) {
      // 发起请求
      console.log('修改成功!')
    } else {
      return false
    }
  })
}
</script>
